package com.glasses.business.pay.wxpay;

import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.util.Xml;

import com.glasses.business.entity.PayInfo;
import com.glasses.business.pay.com.ConstantKeys;
import com.glasses.business.pay.com.L;
import com.glasses.business.pay.com.PayAgent;
import com.glasses.business.pay.com.PayListener;
import com.glasses.business.wxapi.WXPayEntryActivity;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.haitao.common.utils.AppLog;
import org.xmlpull.v1.XmlPullParser;

import java.io.StringReader;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * @author wang
 * @version V1.0
 * @Description: 微信支付工具
 * @date 2016-3-10 下午6:12:37
 */
public class WechatPayHelper {

    private PayReq req;
    private IWXAPI msgApi;
    private PayListener payListener;
    private PayInfo info;

    private final String LOG_TAG = "wachatPayLog";


    public void setOnlieMode(boolean isOnlieMode) {

    }

    public void pay(Activity ac, PayInfo info, PayListener payListener) {
        // 先判断是否安装微信
        if (isAppInstalled(ac, "com.tencent.mm")) {
            msgApi = WXAPIFactory.createWXAPI(ac, null);
            this.payListener = payListener;
            this.info = info;
            WXPayEntryActivity.setPayListener(payListener);
            // 第一步获取id
            GetPrepayIdTask getPrepayId = new GetPrepayIdTask();
            getPrepayId.execute();
        } else {
            if (payListener != null) {
                payListener.onPayFail(PayAgent.PayType.WECHATPAY, PayListener.ERROR_NO_WEICHAT, "没有安装微信");
            }
        }


    }

    private boolean isAppInstalled(Activity ac, String uri) {
        PackageManager pm = ac.getPackageManager();
        boolean installed = false;
        try {
            pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
            installed = true;
        } catch (PackageManager.NameNotFoundException e) {
            installed = false;
        }
        return installed;
    }

    /**
     * 生成签名
     */

    private String genPackageSign(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < params.size(); i++) {
            sb.append(params.get(i).getName());
            sb.append('=');
            sb.append(params.get(i).getValue());
            sb.append('&');
        }
        sb.append("key=");
        sb.append(ConstantKeys.WxPay.API_KEY);


        String packageSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
        L.e(LOG_TAG, packageSign);
        return packageSign;
    }

    private String genAppSign(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < params.size(); i++) {
            sb.append(params.get(i).getName());
            sb.append('=');
            sb.append(params.get(i).getValue());
            sb.append('&');
        }
        sb.append("key=");
        sb.append(ConstantKeys.WxPay.API_KEY);

        String appSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
        L.e(LOG_TAG, appSign);
        return appSign;
    }

    private String toXml(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();
        sb.append("<xml>");
        for (int i = 0; i < params.size(); i++) {
            sb.append("<" + params.get(i).getName() + ">");


            sb.append(params.get(i).getValue());
            sb.append("</" + params.get(i).getName() + ">");
        }
        sb.append("</xml>");

        L.e(LOG_TAG, sb.toString());
        return sb.toString();
    }


    /**
     * 支付准备
     *
     * @author wang
     * @version V1.0
     * @Package com.weixin.paydemo
     * @Description: TODO
     * @date 2016-3-10 下午3:11:19
     */
    private class GetPrepayIdTask extends AsyncTask<Void, Void, Map<String, String>> {

        @Override
        protected void onPreExecute() {

        }

        @Override
        protected void onPostExecute(Map<String, String> result) {
            if (result != null) {

                if ("SUCCESS".equals(result.get("return_code")) && null != result.get("prepay_id")) {
                    //生成支付参数
                    genPayReq(result.get("prepay_id"));
                    // 吊起支付
                    sendPayReq();
                } else {
                    if (payListener != null) {
                        payListener.onPayFail(PayAgent.PayType.WECHATPAY, PayListener.ERROR_SIGN, result.get("return_msg"));
                    }
                }

            } else {
                if (payListener != null) {
                    payListener.onPayFail(PayAgent.PayType.WECHATPAY, PayListener.ERROR_SIGN, "签名错误");
                }
            }
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
        }

        @Override
        protected Map<String, String> doInBackground(Void... params) {

            msgApi.registerApp(ConstantKeys.WxPay.APP_ID);
            String url = String.format("https://api.mch.weixin.qq.com/pay/unifiedorder");
            String entity = genProductArgs();

            L.e(LOG_TAG, entity);

            byte[] buf = Util.httpPost(url, entity);

            String content = new String(buf);
            L.e(LOG_TAG, content);
            Map<String, String> xml = decodeXml(content);
            AppLog.e("微信支付==xml==>" + xml);
            return xml;
        }
    }


    public Map<String, String> decodeXml(String content) {

        try {
            Map<String, String> xml = new HashMap<String, String>();
            XmlPullParser parser = Xml.newPullParser();
            parser.setInput(new StringReader(content));
            int event = parser.getEventType();
            while (event != XmlPullParser.END_DOCUMENT) {

                String nodeName = parser.getName();
                switch (event) {
                    case XmlPullParser.START_DOCUMENT:

                        break;
                    case XmlPullParser.START_TAG:

                        if ("xml".equals(nodeName) == false) {
                            //实例化student对象
                            xml.put(nodeName, parser.nextText());
                        }
                        break;
                    case XmlPullParser.END_TAG:
                        break;
                }
                event = parser.next();
            }

            return xml;
        } catch (Exception e) {
            L.e(LOG_TAG, e.toString());
        }
        return null;

    }


    private String genNonceStr() {
        Random random = new Random();
        return MD5.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
    }

    private long genTimeStamp() {
        return System.currentTimeMillis() / 1000;
    }

    private String genProductArgs() {
        StringBuffer xml = new StringBuffer();

        try {
            String nonceStr = genNonceStr();
            xml.append("</xml>");
            List<NameValuePair> packageParams = new LinkedList<NameValuePair>();
            packageParams.add(new BasicNameValuePair("appid", ConstantKeys.WxPay.APP_ID));
            packageParams.add(new BasicNameValuePair("body", info.getSubject()));
            packageParams.add(new BasicNameValuePair("mch_id", ConstantKeys.WxPay.MCH_ID));
            packageParams.add(new BasicNameValuePair("nonce_str", nonceStr));
            packageParams.add(new BasicNameValuePair("notify_url", info.getNotifyUrl1()));
            packageParams.add(new BasicNameValuePair("out_trade_no", info.getOutTradeNo()));
            packageParams.add(new BasicNameValuePair("spbill_create_ip",info.getNotifyIp()));
            AppLog.e("===========price========="+info.getFinalPrice() * 100);
            String price = String.valueOf((int) (info.getFinalPrice() * 100));
            AppLog.e("===========price========="+price);
            packageParams.add(new BasicNameValuePair("total_fee", price));
            packageParams.add(new BasicNameValuePair("trade_type", "APP"));
            String sign = genPackageSign(packageParams);
            packageParams.add(new BasicNameValuePair("sign", sign));

            String xmlstring = toXml(packageParams);

            return new String(xmlstring.toString().getBytes(), "ISO8859-1");

        } catch (Exception e) {
            L.e("xx", "genProductArgs fail, ex = " + e.getMessage());
            return null;
        }


    }

    private void genPayReq(String prepay_id) {
        req = new PayReq();
        req.appId = ConstantKeys.WxPay.APP_ID;
        req.partnerId = ConstantKeys.WxPay.MCH_ID;
        req.prepayId = prepay_id;
        req.packageValue = "Sign=WXPay";
        req.nonceStr = genNonceStr();
        req.timeStamp = String.valueOf(genTimeStamp());

        List<NameValuePair> signParams = new LinkedList<NameValuePair>();
        signParams.add(new BasicNameValuePair("appid", req.appId));
        signParams.add(new BasicNameValuePair("noncestr", req.nonceStr));
        signParams.add(new BasicNameValuePair("package", req.packageValue));
        signParams.add(new BasicNameValuePair("partnerid", req.partnerId));
        signParams.add(new BasicNameValuePair("prepayid", req.prepayId));
        signParams.add(new BasicNameValuePair("timestamp", req.timeStamp));
        req.sign = genAppSign(signParams);
        L.e(LOG_TAG, signParams.toString());

    }

    private void sendPayReq() {
        msgApi.registerApp(ConstantKeys.WxPay.APP_ID);
        msgApi.sendReq(req);
    }
}
